import React, { Component } from 'react'
import request from '../../util/request'

interface IProps{
    history:any
}

interface IState{
    username:string,
    password:string,
    [propName:string]:any
}

export default class Login extends Component<IProps,IState> {
    state = {
        username:'',
        password:''
    }
    render() {
        let {username,password} = this.state;
        return (
            <div>
                用户名:<input type="text" value={username} name="username" onChange={this.change}></input>
                密码：<input type="text" value={password} name="password" onChange={this.change}/>
                <button onClick={this.login}>登录</button>
            </div>
        )
    }

    change = (e:any) => {
        this.setState({
            [e.target.name]:e.target.value
        })
    }

    //登录
    login = () => {
        let {username,password} = this.state;
        if(username && password){
            request.post('/api/login',{username,password}).then(res => {
                if(res.data.code === 1){
                    alert("登录成功");
                    localStorage.setItem("token",res.data.token);
                    this.props.history.push('/main');
                }
            })
        }else{
            alert("参数有误")
        }
    }
}
